﻿using mozhi.smarterp.AuthorCenter.Departments.Repositories;
using mozhi.smarterp.AuthorCenter.Departments.Sevices;
using Mozhi.Abp.Module.DataLinkage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Guids;
using Volo.Abp.Users;

namespace mozhi.smarterp.AuthorCenter.Departments
{
    public class DepartmentAppService : AuthorCenterAppService, IDepartmentAppService
    {
        private IDepartmentRepository _repository;
        private DepartmentManager _manager;

        public DepartmentAppService(IDepartmentRepository repository, DepartmentManager manager, IDataLinkageRepository dataLinkageRepository) : base(dataLinkageRepository)
        {
            _repository = repository;
            _manager = manager;
        }

        public async Task<DepartmentDto> CreateAsync(DepartmentCreateDto input)
        {
            var department = await _manager.GetAsync(null, input.Code, input.Name, input.ParentId, input.Activated);

            department = await _repository.InsertAsync(department);

            return ObjectMapper.Map<Department, DepartmentDto>(department);
        }


        public async Task DeleteAsync(Guid id)
        {
            var department = await _repository.FindAsync(id);

            if (department == null)
                throw new BusinessException("100000", $"部门：{id}不存在");

            var dataLinkageCount = await _dataLinkageRepository.GetCountAsync(null , id , null);

            if (dataLinkageCount > 0)
                throw new UserFriendlyException("部门存在数据引用，无法删除", AuthorCenterDomainErrorCodes.DataLinkaged, id.ToString());

            await _repository.DeleteAsync(department);
        }


        public async Task<DepartmentDto> GetAsync(Guid id)
        {
            var department = await _repository.GetAsync(id);

            if (department == null)
                throw new BusinessException("100000", $"部门：{id}不存在");

            return ObjectMapper.Map<Department, DepartmentDto>(department);
        }

        public async Task<List<DepartmentDto>> GetListAsync(DepartmentFilter filter)
        {
            var departments = await _repository.GetListAsync();

            return ObjectMapper.Map<List<Department>, List<DepartmentDto>>(departments);
        }

        public async Task<DepartmentDto> UpdateAsync(DepartmentUpdateDto input)
        {
            var department = await _manager.GetAsync(input.Id, input.Code, input.Name, input.ParentId, input.Activated);

            department = await _repository.UpdateAsync(department);

            return ObjectMapper.Map<Department, DepartmentDto>(department);
        }
    }
}
